package com.icesoft.core.common.configurer;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * 通过实现AsyncConfigurer自定义异常线程池，包含异常处理
 * {@link org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration}
 * {@link org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration}
 * WebSocketConfigurationSupport defaultSockJsTaskScheduler return null
 */
@Slf4j
@AllArgsConstructor
public class DefaultPoolAsyncConfigurer implements AsyncConfigurer, DisposableBean {
    @Override
    public Executor getAsyncExecutor() {
        return asyncExecutor;
    }

    private final Executor asyncExecutor;

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new DefaultAsyncExceptionHandler();
    }

    /**
     * 自定义异常处理类
     */
    static class DefaultAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {
            log.error("异步线程池异常方法名 - {}", method.getName());
            log.error(" 异常信息 - ", throwable);
        }

    }

    @Override
    public void destroy() {
        log.info(" shutdown threadPool ...");
    }

}
